﻿using Aliphant.Mvvm.XEvent.Events;
using Aliphant.Mvvm.XEvent.Events.Base.SubScription;
using CommonLibrary.Helper;
using CommonLibrary.UI;
using CuteWallpaperDemo.Models;
using CuteWallpaperDemo.ViewModels;
using DataModel.Contants;
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace CuteWallpaperDemo.Views
{
    /// <summary>
    /// SelectWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SelectWindow : WindowBase
    {
        private ProjectAgent _projectAgent;
        private WindowEvent _windowEvent;
        private bool _isLoad = false;

        SubScriptionToken? _subscriptionToken1;
        SubScriptionToken? _subscriptionToken2;
        SubScriptionToken? _subscriptionToken3;

        public SelectWindow()
        {
            InitializeComponent();
            _projectAgent = ProjectContainer.ProjectAgent;
            _windowEvent = _projectAgent.EventManager.GetEvent<WindowEvent>();

            RegistSubScriptionToken();
        }

        private void RegistSubScriptionToken()
        {
            _subscriptionToken1 = _windowEvent.Subscribe(OnCloseWindow, (p) => p.WindowActionType == WindowActionType.Close && p.EventId == EventIds.OpenAddWindow);
            _subscriptionToken2 = _windowEvent.Subscribe(OnFinishWindow, (p) => p.WindowActionType == WindowActionType.OK && p.EventId == EventIds.OpenAddWindow);
            _subscriptionToken3 = _windowEvent.Subscribe(SelectFileWindow, (p) => p.WindowActionType == WindowActionType.Edit && p.EventId == EventIds.SelectFileDialog);
        }

        private void UnRegistSubScriptionToken()
        {
            _windowEvent.UnSubscribe(_subscriptionToken1);
            _windowEvent.UnSubscribe(_subscriptionToken2);
            _windowEvent.UnSubscribe(_subscriptionToken3);
        }

        private void SelectFileWindow(WindowEvent args)
        {
            WindowHelper.SelectFilesWindow(args);
        }

        private void OnFinishWindow(WindowEvent args)
        {
            if (CallBack is Action<object?> callback)
            {
                callback(args.Data);
            }
            this.Close();
        }

        private void OnCloseWindow(WindowEvent args)
        {
            this.Close();
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            if (!_isLoad)
            {
                if (this.DataContext is SelectWindowViewModel viewModel)
                {

                }
                _isLoad = true;
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            UnRegistSubScriptionToken();
            base.OnClosing(e);
        }

        private void txb_picture_PreviewDragOver(object sender, System.Windows.DragEventArgs e)
        {
            // 检查拖拽内容是否为文件
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effects = DragDropEffects.Copy;
                txb_picture.Background = Brushes.LightBlue; // 视觉反馈
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }
            e.Handled = true;
        }

        private void txb_picture_Drop(object sender, System.Windows.DragEventArgs e)
        {
            // 恢复背景色
            txb_picture.Background = Brushes.White;

            // 获取拖放的文件路径
            if (e.Data.GetData(DataFormats.FileDrop) is string[] filePaths && filePaths.Length > 0)
            {
                // 检查文件扩展名
                var allowedExtensions = new[] { ".png", ".jpg", ".jpeg", ".webp", ".bmp" };
                var validFiles = filePaths.Where(f => allowedExtensions.Contains(Path.GetExtension(f).ToLower()));

                if (validFiles.Any())
                {
                    // 单文件：显示第一个文件路径
                    //txb_picture.Text = validFiles.FirstOrDefault();

                    // 多文件：显示所有文件路径（用分号分隔）
                    txb_picture.Text = string.Join("; ", validFiles);
                }
                else
                {
                    MessageBox.Show("仅支持 .txt 和 .jpg 文件！");
                }

                txb_picture.Focus();
            }
        }
    }
}
